<template>
  <el-dialog
    ref="dialogform"
    :title="addEditName + title"
    :visible.sync="dialogVisible"
    width="78%"
    :before-close="handleClose"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="单据日期" prop="dbilldate">
        <el-date-picker
          class="w100p"
          value-format="yyyy-MM-dd"
          v-model="ruleForm.dbilldate"
          type="date"
          placeholder="选择单据日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="仓库" prop="cwarehouseid">
        <el-select
          class="w100p"
          v-model="ruleForm.cwarehouseid"
          filterable
          placeholder="请选择仓库"
        >
          <el-option
            v-for="(item, index) in StordocList"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="库管员" prop="cwhsmanagerid">
        <el-select
          class="w100p"
          v-model="ruleForm.cwhsmanagerid"
          filterable
          placeholder="请选择库管员"
        >
          <el-option
            v-for="(item, index) in PsndocList"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="领料部门" prop="cdptid">
        <el-select
          class="w100p"
          v-model="ruleForm.cdptid"
          filterable
          placeholder="请选择领料部门"
          @change="handleChangeOrgDept"
        >
          <el-option
            v-for="(item, index) in OrgDeptList"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="elrowBox">
        <el-row v-for="(item, index) in ruleForm.ic_material_b" :key="index">
          <el-col :span="6">
            <el-form-item
              :label="index == 0 ? '物料' : '物料'"
              :prop="`ic_material_b[${index}][cmaterialvid]`"
              :rules="rules.cmaterialvid"
            >
              <el-select
                v-model="item.cmaterialvid"
                class="w100p"
                clearable
                filterable
                placeholder="请选择物料"
                @change="handleChangeMaterial($event, index)"
              >
                <el-option
                  v-for="(s, index) in MaterialList"
                  :key="index"
                  :label="s.name"
                  :value="s.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              :label="index == 0 ? '主计量单位' : '主计量单位'"
              :prop="`ic_material_b[${index}][measdocname]`"
              :rules="rules.measdocname"
            >
              <el-input disabled v-model="item.measdocname"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '辅计量单位' : '辅计量单位'"
              :prop="`ic_material_b[${index}][castunitid]`"
              :rules="rules.castunitid"
            >
              <el-select
                v-model="item.castunitid"
                class="w100p"
                clearable
                filterable
                placeholder="请选择物料辅计量单位"
                @change="handleChangeMaterialconvert($event, index)"
              >
                <el-option
                  v-for="(s, index) in MaterialconvertList[index]"
                  :key="index"
                  :label="s.measdocname"
                  :value="s.measdoccode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '换算率' : '换算率'"
              :prop="`ic_material_b[${index}][vchangerate]`"
              :rules="rules.vchangerate"
            >
              <el-input disabled v-model="item.vchangerate"></el-input>
            </el-form-item>
          </el-col>
                 <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '活鱼品规' : '活鱼品规'"
              :prop="`ic_material_b[${index}][vfree1]`"
              :rules="rules.vfree1"
            >
              <el-select
                v-model="item.vfree1"
                class="w100p"
                clearable
                filterable
                placeholder="请选择活鱼品规"
              >
                <el-option
                  v-for="(s, index) in Defdoc2List"
                  :key="index"
                  :label="s.name"
                  :value="s.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              :label="index == 0 ? '实发主数量' : '实发主数量'"
              :prop="`ic_material_b[${index}][nnum]`"
              :rules="rules.nnum"
            >
              <el-input
                @change="changeNnum($event, index)"
                type="number"
                v-model="item.nnum"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              :label="index == 0 ? '实发辅数量' : '实发辅数量'"
              :prop="`ic_material_b[${index}][nassistnum]`"
              :rules="rules.nassistnum"
            >
              <el-input
                @change="changeNassistnum($event, index)"
                type="number"
                v-model="item.nassistnum"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '应发主数量' : '应发主数量'"
              :prop="`ic_material_b[${index}][nshouldnum]`"
              :rules="rules.nshouldnum"
            >
              <el-input v-model="item.nshouldnum"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '应发辅数量' : '应发辅数量'"
              :prop="`ic_material_b[${index}][nshouldassistnum]`"
              :rules="rules.nshouldassistnum"
            >
              <el-input v-model="item.nshouldassistnum"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              :label="index == 0 ? '批次号' : '批次号'"
              :prop="`ic_material_b[${index}][vbatchcode]`"
              :rules="rules.vbatchcode"
            >
              <el-select
                v-model="item.vbatchcode"
                class="w100p"
                clearable
                filterable
                placeholder="请选择批次号"
                @change="changeVbatchcode($event, index)"
              >
                <el-option
                  v-for="(s, index) in BatchcodeList"
                  :key="index"
                  :label="s.vbatchcode"
                  :value="s.pk_batchcode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              :label="index == 0 ? '养殖批次号' : '养殖批次号'"
              :prop="`ic_material_b[${index}][vproductbatch]`"
            >
              <el-input v-model="item.vproductbatch"></el-input>
            </el-form-item>
          </el-col>
   
          <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '条数' : '条数'"
              :prop="`ic_material_b[${index}][vbdef1]`"
              :rules="rules.vbdef1"
            >
              <el-input v-model="item.vbdef1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              :label="index == 0 ? '均重' : '均重'"
              :prop="`ic_material_b[${index}][vbdef2]`"
              :rules="rules.vbdef2"
            >
              <el-input v-model="item.vbdef2"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <i
              class="icon el-icon-circle-plus-outline"
              @click.stop="addMaterial()"
            ></i>
            <i
              v-show="index"
              class="icon el-icon-remove-outline"
              @click.stop="delMaterial(index)"
            ></i>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import ncqueryApi from "@/api/nc-query/index.js";
import ncbasicinfoApi from "@/api/nc-basic-info/index.js";
export default {
  components: {},
  props: {
    addEditFlag: {
      type: String,
      default: () => {
        return "add";
      },
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    title: {
      type: String,
      default: () => {
        return "操作表单";
      },
    },
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    varietyList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      addEditName: "添加",
      addEditApi: "",
      StordocList: [], //仓库
      PsndocList: [], //库管员
      OrgDeptList: [], //领料部门
      MaterialList: [], //物料
      BatchcodeList: [], //批次
      MaterialconvertList: [], //物料辅计量单位
      Defdoc2List: [], //活鱼品规
      pk_org: JSON.parse(localStorage.getItem("ncOrg")) || null,
      ruleForm: {
        ic_material_b: [{}],
      },
      rules: {
        dbilldate: [
          {
            required: true,
            message: "请选择单据日期",
            trigger: ["change", "blur"],
          },
        ],
        cwarehouseid: [
          {
            required: true,
            message: "请选择仓库",
            trigger: ["change", "blur"],
          },
        ],
        cwhsmanagerid: [
          {
            required: true,
            message: "请选择库管员",
            trigger: ["change", "blur"],
          },
        ],
        cdptid: [
          {
            required: true,
            message: "请选择领料部门",
            trigger: ["change", "blur"],
          },
        ],
        cmaterialvid: [
          {
            required: true,
            message: "请选择物料",
            trigger: ["change", "blur"],
          },
        ],
        measdocname: [
          {
            required: true,
            message: "主单位不能为空",
            trigger: ["change", "blur"],
          },
        ],
        castunitid: [
          {
            required: true,
            message: "辅单位不能为空",
            trigger: ["change", "blur"],
          },
        ],
        vchangerate: [
          {
            required: true,
            message: "换算率不能为空",
            trigger: ["change", "blur"],
          },
        ],
        nassistnum: [
          {
            required: true,
            message: "请输入实发数量",
            trigger: ["change", "blur"],
          },
          {
            required: true,
            pattern: /^\+?[1-9]\d*$/,
            message: "请输入大于0的正整数",
            trigger: ["change", "blur"],
          },
        ],
        nnum: [
          {
            required: true,
            message: "请输入实发主数量",
            trigger: ["change", "blur"],
          },
          {
            required: true,
            pattern: /^\+?[1-9]\d*$/,
            message: "请输入大于0的正整数",
            trigger: ["change", "blur"],
          },
        ],
        vbdef1: [
          {
            required: true,
            message: "请输入条数",
            trigger: ["change", "blur"],
          },
          {
            required: true,
            pattern: /^\+?[1-9]\d*$/,
            message: "请输入大于0的正整数",
            trigger: ["change", "blur"],
          },
        ],
        vbdef2: [
          {
            required: true,
            message: "请输入均重",
            trigger: ["change", "blur"],
          },
          {
            required: true,
            pattern: /^\+?[1-9]\d*$/,
            message: "请输入大于0的正整数",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  computed: {},
  watch: {
    dialogVisible(v) {
      v && this.initData();
    },
  },

  mounted() {},
  methods: {
    initData() {
      if (this.addEditFlag == "add") {
        this.resetForm();
        this.queryStordoc();
        this.queryOrgDept(); //部门
        this.queryPsndoc();
        this.queryMaterial(); //物料
        // this.queryMaterialconvert(); //物料辅计量单位
        this.queryDefdoc2(); //活鱼品规
        this.ruleForm = {
          pk_group: "SSAGROUP",
          pk_org: JSON.parse(localStorage.getItem("ncOrg")||"{}") || null,
          ctrantypeid: "4D-01",
          vtrantypecode: "4D-01",
          ic_material_b: [{}],
        };
        this.addEditApi = ncqueryApi.materialoutSave;
        this.addEditName = "添加";
      }
    },

    //仓库
    queryStordoc() {
      let params = {
        pk_org: this.pk_org,
      };
      ncbasicinfoApi.queryStordoc(params).then((res) => {
        if (res.success) {
          this.StordocList = res.data || [];
        }
      });
    },

    //部门
    queryOrgDept() {
      let params = {
        pk_org: this.pk_org,
      };
      ncbasicinfoApi.queryOrgDept(params).then((res) => {
        if (res.success) {
          this.OrgDeptList = res.data || [];
        }
      });
    },

    //库管员
    queryPsndoc() {
      let params = {
        pk_org: this.pk_org,
      };
      ncbasicinfoApi.queryPsndoc(params).then((res) => {
        if (res.success) {
          this.PsndocList = res.data || [];
        }
      });
    },

    //物料
    queryMaterial() {
      let params = {
        pk_parent: "1001A110000000003G5C",
      };
      ncbasicinfoApi.queryMaterial(params).then((res) => {
        if (res.success) {
          this.MaterialList = res.data || [];
        }
      });
    },
    //批次号查询
    queryBatchcode(value) {
      let params = {
        entity: {
          ...value,
        },
        page: 1,
        size: 10,
      };
      ncqueryApi.queryBatchcode(params).then((res) => {
        if (res.success) {
          this.BatchcodeList = res.data || [];
        }
      });
    },

    //物料辅计量单位
    queryMaterialconvert(value, index) {
      let params = value;
      ncbasicinfoApi.queryMaterialconvert(params).then((res) => {
        if (res.success) {
          let list = res.data || [];
          let newlist = [];
          for (let index = 0; index < list.length; index++) {
            let obj = list[index];
            if (
              obj.pk_measdoc !== this.MaterialconvertList[index][0].pk_measdoc
            ) {
              newlist.push(obj);
            }
          }
          this.MaterialconvertList[index].push(...newlist);
        }
        console.log(
          this.MaterialconvertList,
          "MaterialconvertListMaterialconvertList"
        );
      });
    },

    //活鱼品规
    queryDefdoc2() {
      let params = {
        // pk_parent: "1001A110000000003G5C",
      };
      ncbasicinfoApi.queryDefdoc2(params).then((res) => {
        if (res.success) {
          this.Defdoc2List = res.data || [];
        }
      });
    },

    handleChangeOrgDept() {
      this.$set(this.ruleForm, "cdptvid", this.ruleForm.cdptid);
    },

    //物料更改
    handleChangeMaterial(e, index) {
      let rut = this.MaterialList.find((item) => {
        return e == item.code;
      });
      //   this.MaterialconvertList[index] = [rut];
      this.$set(this.MaterialconvertList, index, [rut]);
      this.$set(this.ruleForm.ic_material_b[index], "castunitid", "");
      this.$set(this.ruleForm.ic_material_b[index], "vchangerate", "");
      this.queryMaterialconvert({ pk_material: rut.pk_material }, index);
      //   this.queryBatchcode({ cmaterialvid: rut.pk_material });
      this.$set(this.ruleForm.ic_material_b[index], "cunitid", rut.measdoccode);
      this.$set(
        this.ruleForm.ic_material_b[index],
        "measdocname",
        rut.measdocname
      );

      console.log(e, index, rut, this.MaterialconvertList);
    },

    //批次更改
    changeVbatchcode(e, index) {
      let rut = this.BatchcodeList.find((item) => {
        return e == item.pk_batchcode;
      });
      console.log(e, index, rut, "批次更改批次更改");
    },

    //辅计量单位更改
    handleChangeMaterialconvert(e, index) {
      let rut = this.MaterialconvertList[index].find((item) => {
        return e == item.measdoccode;
      });
      this.$set(
        this.ruleForm.ic_material_b[index],
        "vchangerate",
        rut.measrate || rut.materialspec
      );
      console.log(e, index, rut);
    },

    //实发主数量更改
    changeNnum(e, index) {
      console.log(e, index, "实发主数量更改");
    },

    //实发数量更改
    changeNassistnum(e, index) {
      console.log(e, index);
    },

    handleChangePlantVariety() {
      let rut = this.varietyList.find((item) => {
        return this.ruleForm.fishVarietyId == item.fishVarietyId;
      });
      let name = rut?.name;
      this.$set(this.ruleForm, "varietyName", name || "");
    },
    //提交表单
    submitForm() {
      console.log(
        this.ruleForm,
        this.ic_material_b,
        "this.ruleFormthis.ruleForm"
      );
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log(valid);
          // this.addEditApi({ ...this.ruleForm }).then(res => {
          //     let msg = res.success ? '操作成功' : '操作失败'
          //     this.$message[res.success ? 'success' : 'warning'](res.message || msg)
          //     res.success && this.cancel();
          //     //提交数据时删除保存的记录
          //     res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
          // }).catch(err => {
          //     this.$message.error(err)
          // })
        } else {
          return false;
        }
      });
    },

    addMaterial() {
      let length = this.ruleForm.ic_material_b?.length || 0;
      if (length) {
        this.$set(this.ruleForm.ic_material_b, length, {
          weight: null,
          num: null,
          cmaterialvid: null,
        });
      }
    },
    delMaterial(index) {
      let list = this.ruleForm.ic_material_b;
      list.splice(index, 1);
      //   this.ruleForm.ic_material_b = JSON.parse(JSON.stringify(list));
      this.$set(this.ruleForm, "ic_material_b", list);
    },
    //重置
    resetForm() {
      this.ruleForm = {};
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
    },
    //取消关闭
    cancel() {
      this.resetForm();
      this.$emit("closeDialog");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.resetForm();
          this.cancel();
        })
        .catch((_) => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.line {
  border-bottom: 1px solid #e6e6e6;
}

.icon {
  font-size: 20px;
  line-height: 29px;
  cursor: pointer;
}

::v-deep .noLabel {
  .el-form-item {
    .label {
      display: none;
    }

    .el-form-item__content {
      margin: 0;
    }
  }
}
.demo-ruleForm {
  .elrowBox {
    max-height: 350px;
    overflow-y: auto;
  }
}
</style>